home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!usenet
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Derivation and calling virtual functions
- Date: Fri, 29 Mar 1996 14:09:59 -0500
- Organization: Datalytics, Inc
- Message-ID: <315C3587.293F@datalytics.com>
- References: <graphix.828032689@spiff.cc.iastate.edu>
- NNTP-Posting-Host: 204.62.224.71
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Kent A Vander Velden wrote:
- >
- > Say we have the following:
- >
- > class Base {
- > public:
- > virtual void func() { // some stuff }
- > virtual void write() { func(); };
- > };
- >
- > class Derived : public Base {
- > public:
- > void func() { // some stuff }
- > write(); { Base::func(); }
- > };
- >
- > Derived inst;
- >
- > Now, when I call inst.write() it in turn calls Bass::write() which in
- > turn calls Base::func(). Is there a way to instead have it call
- > Derived::func() if the instance is of type Derived? I hoped the
- > virtual keyword would help in this case.
- >
-
- inst.write() calls Derived::write(). That function is written
- to call Base::func().
-
- To do what you want, write your classes like this:
-
- class B
- {
- public:
- virtual
- void func(void);
- void write(void) { func(); };
- };
- class D : public B
- {
- public:
- virtual
- void func(void);
- };
-
- Then, write code to use it like this:
-
- D itD;
- B& it = itD;
- it.write();
-
- or like this:
-
- B* pIt = new D;
- pIt->write();
-
- The result is that it.write() and pIt->write() will call
- B::write(). In turn, it will call this->func(). Since func is
- a virtual function and you're calling it though a reference or
- pointer to B, the compiler looks up the address of func from the
- vtable. Since it (pIt) actually references (points to) a D,
- this->func() will call D::func().
- QED
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc. | stew@datalytics.com
-